#include "scheduler.h"

#include <iostream>
#include <string>
#include <thread>
#include <vector>

#include "interface.h"

bool Workflow::execute() {
  if (is_completed_ || is_failed_) return false;

  if (current_step_idx_ >= steps_.size()) {
    is_completed_ = true;
    std::cout << "\n[" << name_ << "] 工作流全部完成！" << std::endl;
    return false;
  }

  auto &current_step = steps_[current_step_idx_];
  int progress = 0;

  bool step_success = current_step->execute(progress);

  if (!step_success) {
    is_failed_ = true;
    std::cout << "[" << name_ << "] 工作流失败于步骤："
              << current_step->getName() << std::endl;
    return false;
  }

  if (current_step->isCompleted()) {
    std::cout << "[" << name_ << "] 步骤完成：" << current_step->getName()
              << "（进度：" << progress << "%）" << std::endl;
    current_step_idx_++;
  } else {
    std::cout << "[" << name_ << "] 步骤进度：" << current_step->getName()
              << " " << progress << "%" << std::endl;
  }

  return true;
}

void Scheduler::start() {
  std::cout << "[调度器] 启动" << std::endl;
  std::cout << "[调度器] 执行间隔：" << interval_.count() << "ms，工作流数："
            << workflows_.size() << std::endl;

  bool all_done = false;
  while (!all_done) {
    all_done = true;
    for (auto &workflow : workflows_) {
      if (!workflow->isCompleted() && !workflow->isFailed()) {
        workflow->execute();
        all_done = false;
      }
    }

    if (!all_done) {
      std::this_thread::sleep_for(interval_);
    }
  }

  std::cout << "\n[调度器] 所有工作流结束" << std::endl;
}
